/*
 * Copyright (c) 2014. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.jspx.txweb.dao.impl;

import org.slf4j.Logger;
import com.jspx.boot.environment.Environment;
import org.slf4j.LoggerFactory;
import com.jspx.io.AbstractRead;
import com.jspx.io.AutoReadTextFile;
import com.jspx.scriptmark.XmlEngine;
import com.jspx.scriptmark.core.TagNode;
import com.jspx.scriptmark.parse.XmlEngineImpl;
import com.jspx.sioc.tag.MapElement;
import com.jspx.sioc.tag.ValueElement;
import com.jspx.sober.Criteria;
import com.jspx.sober.criteria.expression.Expression;
import com.jspx.sober.criteria.projection.Projections;
import com.jspx.sober.jdbc.JdbcOperations;
import com.jspx.sober.ssql.SSqlExpression;
import com.jspx.txweb.dao.OptionDAO;
import com.jspx.txweb.table.OptionBundle;
import com.jspx.utils.ArrayUtil;
import com.jspx.utils.StringUtil;
import com.jspx.zhex.spell.ChineseUtil;
import java.io.File;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yuan on 14-2-16.
 *
 * com.jspx.txweb.dao.impl.OptionDAOImpl
 */
public class OptionDAOImpl extends JdbcOperations implements OptionDAO {
    private static final Logger log = LoggerFactory.getLogger(OptionDAOImpl.class);
    private static Map<String,String> spaceMap = new LinkedHashMap<String, String>();
    public OptionDAOImpl()
    {

    }

    private String folder;
    public String getFolder() {
        return folder;
    }

    public void setFolder(String folder) throws Exception {
        this.folder = folder;
        //载入目录索引
        if (!spaceMap.isEmpty()) return;
        File file = new File(this.folder,"index.xml");
        if (!file.isFile()) return;

        AbstractRead read = new AutoReadTextFile();
        read.setEncode(Environment.defaultEncode);
        read.setFile(file);

        XmlEngine xmlEngine = new XmlEngineImpl();
        xmlEngine.putTag("map",MapElement.class.getName());
        MapElement mapElement = (MapElement)xmlEngine.createTagNode(read.getContent());
        List<TagNode> valueList = mapElement.getValueList();
        spaceMap.clear();
        for (TagNode aList : valueList)
        {
            ValueElement valueElement = (ValueElement) aList;
            spaceMap.put(valueElement.getKey(),valueElement.getValue());
        }
        valueList.clear();
    }


    public Map<String, String> getSpaceMap() {
        return spaceMap;
    }

    private String namespace = StringUtil.empty;
    public void setNamespace(String namespace)
    {
        this.namespace = namespace;
    }

    public String getNamespace()
    {
        return namespace;
    }


    public String getCaption()
    {
        return spaceMap.get(namespace);
    }


    public int storeDatabase() throws Exception
    {
        int i=0;
        createCriteria(OptionBundle.class).delete(false);
        for (String key:spaceMap.keySet())
        {
            File file = new File(this.folder,key+".xml");
            if (!file.isFile()) continue;

            AbstractRead read = new AutoReadTextFile();
            read.setEncode(Environment.defaultEncode);
            read.setFile(file);
            String xml = read.getContent();
            if (StringUtil.isNULL(xml)) continue;
            XmlEngine xmlEngine = new XmlEngineImpl();
            xmlEngine.putTag("map",MapElement.class.getName());
            MapElement mapElement = (MapElement)xmlEngine.createTagNode(xml);
            List<TagNode> valueList = mapElement.getValueList();
            for (TagNode aList : valueList)
            {
                ValueElement valueElement = (ValueElement) aList;
                OptionBundle optionBundle = new OptionBundle();
                optionBundle.setCode(valueElement.getKey());
                optionBundle.setName(valueElement.getValue());
                optionBundle.setSelected(valueElement.getSelected()?1:0);
                optionBundle.setDescription(valueElement.getKey() + " " + valueElement.getValue());
                optionBundle.setNamespace(key);
                optionBundle.setSpelling(ChineseUtil.getFullSpell(optionBundle.getName(), ""));
                optionBundle.setSortType(StringUtil.toInt(StringUtil.getNumber(valueElement.getKey())));
                optionBundle.setPutName(Environment.SYSTEM_NAME);
                optionBundle.setPutUid(Environment.SYSTEM_ID);
                optionBundle.setIp("127.0.0.1");
                i=i+super.save(optionBundle);

            }
            valueList.clear();
        }
        return i;

    }
    /**
     *
     * @param id    id
     * @return 载入
     * @throws Exception
     */
    public Object load(Long id) throws Exception
    {
        return super.load(OptionBundle.class,id);
    }
    /**
     * @param ids  id
     * @return     删除
     * */
    public boolean delete(Long[] ids) throws Exception
    {
        if (ArrayUtil.isEmpty(ids)) return false;
        try
        {
            for (Long id : ids)
            {
                OptionBundle optionBundle =  (OptionBundle)super.get(OptionBundle.class, id);
                if (optionBundle != null&& optionBundle.getNamespace().equalsIgnoreCase(namespace)) super.delete(optionBundle);
            }
        } catch (Exception e)
        {
            log.error(ArrayUtil.toString(ids,StringUtil.COMMAS),e);
            return false;
        }
        return true;
    }


    /**
     * @param id  id
     * @return   设置默认选项
     * */
    public boolean updateSelected(Long id) throws Exception
    {
        if (id<=0) return false;
        try
        {
            OptionBundle optionBundle =  (OptionBundle)super.get(OptionBundle.class, id);
            if (optionBundle ==null) return false;
            if (optionBundle.getNamespace().equalsIgnoreCase(namespace))
            {
                Map<String,Object> valueMap = new LinkedHashMap<String, Object>();
                valueMap.put("selected",0);
                if (super.createCriteria(OptionBundle.class).add(Expression.eq("namespace", optionBundle.getNamespace())).update(valueMap)>0)
                {
                    optionBundle.setSelected(1);
                    super.update(optionBundle,new String[]{"selected"});
                }
            }

        } catch (Exception e)
        {
            log.error(id + "",e);

            return false;
        }
        return true;
    }

    /**
     * @param ids id
     * @param sortType 排序
     * @return  更新排序
     */
    public boolean updateSortType(Long[] ids, int sortType) throws Exception
    {
        if (ArrayUtil.isEmpty(ids)) return false;
        try
        {
            for (Long id : ids)
            {
                OptionBundle optionBundle =  (OptionBundle)get(OptionBundle.class, id);
                if (optionBundle != null&& optionBundle.getNamespace().equalsIgnoreCase(namespace))
                {
                    optionBundle.setSortType(sortType);
                    super.update(optionBundle, new String[]{"sortType"});
                }
            }
        } catch (Exception e)
        {
            log.error(ArrayUtil.toString(ids,StringUtil.COMMAS),e);
            return false;
        }
        return true;
    }

    /**
     *
     * @param ids  id
     * @return 更新排序日期
     */
    public boolean updateSortDate(Long[] ids) throws Exception
    {
        if (ArrayUtil.isEmpty(ids)) return false;
        try
        {
            for (Long id : ids)
            {
                OptionBundle optionBundle =  (OptionBundle)get(OptionBundle.class, id);
                if (optionBundle != null&& optionBundle.getNamespace().equalsIgnoreCase(namespace))
                {
                    optionBundle.setSortDate(new Date());
                    super.update(optionBundle, new String[]{"sortDate"});
                }
            }
        } catch (Exception e)
        {
            log.error(ArrayUtil.toString(ids,StringUtil.COMMAS),e);
            return false;
        }
        return true;
    }

    /**
     * @param field 字段
     * @param find 查询条件
     * @param term 条件
     * @param sortString 排序
     * @param page     页数
     * @param count   返回数量
     * @return  返回列表
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public List getList(String[] field,String[] find,String term,String sortString,int page, int count) throws Exception
    {
        if (StringUtil.isNULL(sortString)) sortString="createDate:D";
        Criteria criteria = createCriteria(OptionBundle.class);
        if (!ArrayUtil.isEmpty(find)&& !ArrayUtil.isEmpty(field)) {
            criteria = criteria.add(Expression.find(field, find));
        }
        if (!StringUtil.isNULL(namespace)) {
            criteria = criteria.add(Expression.eq("namespace", namespace));
        }
        criteria = SSqlExpression.getTermExpression(criteria, term);
        return SSqlExpression.getSortOrder(criteria, sortString).setCurrentPage(page).setTotalCount(count).list(false);
    }


    /**
     *
     * @param field 字段
     * @param find 查询条件
     * @param term 条件

     * @return    得到记录条数
     * @throws Exception
     */
    public int getCount(String[] field,String[] find,String term) throws Exception
    {
        Criteria criteria = createCriteria(OptionBundle.class);
        if (!ArrayUtil.isEmpty(find)&& !ArrayUtil.isEmpty(field)) {
            criteria = criteria.add(Expression.find(field,find));
        }
        if (!StringUtil.isNULL(namespace)) {
            criteria = criteria.add(Expression.eq("namespace", namespace));
        }
        criteria = SSqlExpression.getTermExpression(criteria, term);
        return criteria.setProjection(Projections.rowCount()).intUniqueResult();
    }


    @SuppressWarnings("unchecked")
    public OptionBundle getSelected() throws Exception
    {
        Criteria criteria = createCriteria(OptionBundle.class).add(Expression.eq("selected",1));
        if (!StringUtil.isNULL(namespace)) {
            criteria = criteria.add(Expression.eq("namespace", namespace));
        } else return new OptionBundle();
        return (OptionBundle)criteria.objectUniqueResult(false);
    }

    @SuppressWarnings("unchecked")
    public OptionBundle getOptionValue(String key) throws Exception
    {
        Criteria criteria = createCriteria(OptionBundle.class).add(Expression.eq("code",key));
        if (!StringUtil.isNULL(namespace)) {
            criteria = criteria.add(Expression.eq("namespace", namespace));
        } else return new OptionBundle();
        return (OptionBundle)criteria.objectUniqueResult(false);
    }



}